<?php
/**
 * 函数集合
 * User: Administrator
 * Date: 2018/10/29/029
 * Time: 10:05
 */

use App\Contracts\LogContract;
use App\Contracts\QrcodeContract;
use App\Models\Base\SysRegion;
use App\Models\Base\SysSerial;
use App\Models\Base\SysSite;
use App\Models\Crm\CrmCard;
use App\Models\Crm\CrmCardUser;
use App\Models\Crm\CrmUser;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Cookie;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

if (! function_exists('include_route_files')) {
    /**
     * Loops through a folder and requires all PHP files
     * Searches sub-directories as well.
     *
     * @param $folder
     */
    function include_route_files($folder)
    {
        try {
            $rdi = new recursiveDirectoryIterator($folder);
            $it = new recursiveIteratorIterator($rdi);
            while ($it->valid()) {
                if (! $it->isDot() && $it->isFile() && $it->isReadable() && $it->current()->getExtension() === 'php') {
                    require $it->key();
                }
                $it->next();
            }
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
}

if(!function_exists('curl_post')) {
    /**
     * @param $url
     * @param $data
     * @param array $header
     * @return mixed
     * 通过curl函数传递数据
     */
    function curl_post($url,$data,$header=[])
    {
        $header = !empty($header) && is_array($header) ? $header : [];
        $data = http_build_query($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}



/**
 * 获取域名
 */
if(!function_exists('get_domain')){
    function get_domain($name)
    {
        $url = env('APP_URL');
        $suffix = strpos($url, 'localhost') ? '.cw100.la' : strstr($url, '.');
        return $name=='web' ? 'www'.$suffix : strtolower($name).$suffix;
    }
}

/**
 * @param $html
 * 生成目录的html数据
 */

if(!function_exists('list_to_html')){
    function list_to_html($collection, &$html = '', $column = 'title', $child = 'children', $group = null)
    {
        foreach($collection as $item){
            $class = $item['checked']==1 ? 'bg-blue' : '';
            $html .= '<li>'.'<span class="tree-item">'.'<a class="show-self '.$class.'" data-id="'.$item->id.'"><i class="iconfont icon-wenjian"></i><span class="file-name">'.$item->$column.'</span></a>'.'</span>';
            if($item->$child){
                $html .= '<ul>';
                list_to_html($item->$child, $html, $column);
                $html .= '</ul>';
            }
            $html .= '</li>';
        }
        return $html;
    }
}

/**
 *  获取在线编辑器或图片上传目录
 */
if(!function_exists('get_upload_base_path')){
    function get_upload_base_path($guard = 'admin')
    {
        $directory = $guard.DIRECTORY_SEPARATOR;
        if($guard=='admin'){
            $directory .= auth($guard)->user()['id'].DIRECTORY_SEPARATOR;
        }
        if($guard=='tenant'){
            $directory .= auth($guard)->user()['tenant_id'].DIRECTORY_SEPARATOR;
        }
        $directory .= date('Y').DIRECTORY_SEPARATOR.date('m').DIRECTORY_SEPARATOR.date('d').DIRECTORY_SEPARATOR;
        $realPath = storage_path('app'.DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR.$directory);
        check_dir($realPath);
        return $realPath;
    }
}

/**
 * 检查目录,没有的话创建目录
 */
if(!function_exists('check_dir')){
    function check_dir($dir)
    {
        if(!file_exists($dir)){
            $oldumask = umask(0);
            mkdir($dir, 0777, true);
            umask($oldumask);
        }
    }
}

/**
 * 上传图片base64
 */
if(!function_exists('uploadBase64')){
    function uploadBase64($base64, $guard = 'web')
    {
        $base64Image = str_replace(' ', '+', $base64);
        //post的数据里面，加号会被替换为空格，需要重新替换回来，如果不是post的数据，则注释掉这一行
        if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64Image, $result)){
            if(empty($result[2]) || !in_array($result[2], ['jpg', 'jpeg', 'png'])){
                return false;
            }
            //匹配成功
            $imageName = uniqid().'.'.$result[2];
            $path = get_upload_base_path($guard);
            check_dir($path);
            $imageFile = $path.$imageName;
            //服务器文件存储路径
            if(file_put_contents($imageFile, base64_decode(str_replace($result[1], '', $base64Image)))){
                $length = strlen(base64_decode(str_replace($result[1], '', $base64Image)));
                $size = $length-$length/8*2;
                return ['path' => get_upload_url($imageFile), 'size' => $size];
            }
        }
        return false;
    }
}

// 判断是否是在微信浏览器里
function isWeixinBrowser()
{
    $agent = $_SERVER ['HTTP_USER_AGENT'];
    if(!strpos($agent, "icroMessenger")){
        return false;
    }
    return true;
}

/**
 * 上传图片url地址
 */
if(!function_exists('get_upload_url')){
    function get_upload_url($realpath)
    {
        $path = str_replace('\\', '/', str_replace(storage_path(), '', $realpath));
        if(preg_match('#app\/public#', $path)){
            return '/storage'.str_replace('/app/public', '', $path);
        }
        return $path;
    }
}
/**
 * @param $realpath
 * @return mixed|string
 */
if(!function_exists('get_storage_url')){

    function get_storage_url($realpath)
    {
        $path = str_replace('\\', '/', str_replace(storage_path(), '', $realpath));
        $url = env('APP_API_URL2');
        $url2 = env('APP_API_URL');
        if(strpos($path,$url)!==false){
            return str_replace($url, '', $path);
        }
        if(strpos($path,$url2)!==false){
            return str_replace($url2, '', $path);
        }
        return $path;
    }
}
/**
 * 模型依赖
 */
if(!function_exists('get_modules_depend')){
    function get_modules_depend($modules)
    {
        return $modules->each(function(&$item) use ($modules){
            $item->depend = 0;
            $key = value(function() use ($item){
                $keys = explode('.', $item->name);
                array_pop($keys);
                return implode('.', $keys);
            });

            if(!empty($module = $modules->where('name', $key)->first())){
                $item->depend = $module->id;
            }
        });
    }
}

/**
 * 未登录用户信息
 */
if(!function_exists('get_logout_user_key')){
    function get_logout_user_key()
    {
        $userKey = Cookie::get('user_key');
        if(empty($userKey)){
            $userKey = uniqid('', true);
            Cookie::forever('user_key', $userKey);
        }
        return $userKey;
    }
}

/**
 * 配置信息设置
 */
if(!function_exists('tenant_setting')){
    function tenant_setting($key, $tenantId, $data = null)
    {
        $key = str_replace('_', '.', $key);
        $config = app(\App\Contracts\ConfigContract::class);
        if(!is_null($data)){
            return $config->set($key, $tenantId, $data);
        }else{
            return $config->get($key, $tenantId);
        }
    }
}

/**
 * 获取城市站点信息
 */
if(!function_exists('get_site_by_ip')){
    function get_site_by_ip($ip)
    {
        try{
            $site = app('cw100.site')->visit($ip);
            if($site==false) throw new Exception;
            return SysSite::find($site);
        }catch(\Exception $ex){
            return SysSite::getDefaultSite();
        }
    }
}

/**
 * 获取城市地质
 */
if(!function_exists('get_site_by_request')){
    function get_site_by_request($request)
    {
        try{
            if(is_mobile()){
                $site = $request->cookie('site_cookie_key');
            }else{
                $site = $request->cookie('VISITOR-SITE-'.ip2long($request->ip()));
            }
            if($site==false) throw new Exception;
            $result = SysSite::find($site);
            if($result){
                return $result;
            }
            throw new Exception;
        }catch(\Exception $ex){
            return SysSite::getDefaultSite();
        }
    }
}

/**
 * 页面显示二维码数据
 */
if(!function_exists('qrcode')){
    function qrcode($model, $url)
    {
        $qrcode = app(QrcodeContract::class)->generate($model, $url);
        return 'data:image/png;base64, '.base64_encode($qrcode);
    }
}

/**
 * 正常二维码
 */
if(!function_exists('normal_qrcode')){
    function normal_qrcode($url, $format = 'svg', $size = 800, $logo = false)
    {
        if($format=='svg'){
            return QrCode::size($size)->generate($url);
        }
        if($format=='png'){
            $qrcode = QrCode::format($format)->size($size);
            if($logo){
                $qrcode = $qrcode->merge('/public/images/login-mini.png');
            }
            return 'data:image/png;base64,'.base64_encode($qrcode->generate($url));
        }

        return QrCode::format($format)->size($size)->generate($url);
    }
}

/**
 * 获取二维码下载地址
 */
if(!function_exists('get_qrcode_download')){
    function get_qrcode_down($model)
    {
        $ticket = hash('ripemd128', $model['id'].get_class($model));
        return '//'.get_domain('api').'/qrcode/download/'.$ticket;
    }
}

if(!function_exists('get_qrcode_download_url')){
    function get_qrcode_down_url($url)
    {
        $ticket = hash('ripemd128', $url);
        return response()->stream(function() use ($url){
            echo QrCode::encoding('UTF-8')->format('png')->size(500)->generate($url);
        }, 200, ["Content-type" => "image/png", "Content-Disposition" => "attachment; filename=".$ticket.".png"]);
    }
}

//获取http地址
if(!function_exists('get_http_url')){
    function get_http_url($path, $domain = 'www',$prefix = 'http')
    {
        return $prefix.'://'.get_domain($domain).'/'.$path;

        //        return '//'.str_replace('http://', '', get_domain($domain)).'/'.$path;
    }
}

/**
 * 处理递归1对多关联数量的查询
 *
 * 比如：经营类目下的商品数量
 */
if(!function_exists('get_recursions')){
    function get_recursions($node, $lists, $relation = null)
    {

        if($relation!=null){
            $lists->load($relation);
            $count = $node->$relation->where('type',\App\Models\Goods\GdsGoods::GOODS_TYPE_NORMAL)->count();
        }else{
            $count = 0;
        }
        $lists = $lists->filter(function($item) use ($node, $relation, &$count){
            $key = $node['position'].',tr_'.$node['id'];
            if(starts_with($item['position'], $key)){
                $count += $item->$relation->where('type',\App\Models\Goods\GdsGoods::GOODS_TYPE_NORMAL)->count();
                return true;
            }
            return false;
        });
        if($relation==null) return $lists->pluck('id')->toArray();

        return $count;
    }
}

/**
 * 树形列表
 *
 * @param array $list
 *            数据库原始数据
 * @param array $res_list
 *            返回的结果数组
 * @param int $pid
 *            上级ID
 * @param int $level
 *            当前处理的层级
 */
if(!function_exists('list_tree')){

    function list_tree($list, &$res_list, $pid = 0, $level = 0)
    {
        foreach($list as $k => $v){
            if(intval($v['parent_id'])!=$pid){
                continue;
            }

            if($level > 0){
                $space = '';
                for($i = 1; $i < $level; $i++){
                    $space .= '──';
                }
                $v['name'] = '├──'.$space.$v['name'];
            }

            $v['level'] = $level;
            $res_list[] = $v;
            unset($list[$k]);

            list_tree($list, $res_list, $v['id'], $level+1);
        }
    }
}
/**
 * @param $province
 * @param $city
 * @param $arrea
 * @return array
 */
if(!function_exists('get_address_data')){

    function get_address_data($province, $city, $arrea)
    {
        return [$province => get_region($province)['name'], $city => get_region($city)['name'], $arrea => get_region($arrea)['name']];
    }
}

if(!function_exists('get_address')){
    /**
     * @param array/string $region 省市区信息
     * @param string $address 地址信息
     *
     * @return string
     */
    function get_address($region, $address = '')
    {
        if(!is_array($region)){
            $region = explode(',', $region);
        }
        $cache_key = implode('-', $region);
        if(Cache::has($cache_key)){
            return Cache::get($cache_key) . (!empty($address) ? ' ' . $address : '');
        }
        $data = SysRegion::whereIn('id', $region)->get()->pluck('name')->toArray();
        Cache::forever($cache_key, implode(' ', $data));
        return implode(' ', $data) . (!empty($address) ? ' ' . $address : '');
    }
}

/**
 * @param $regionId
 * @return mixed
 * 获取region数据
 */
if(!function_exists('get_region')){

    function get_region($regionId)
    {
        return SysRegion::find($regionId);
    }
}
/**
 * @param $table
 * @return string
 * 生成编码
 */
if(!function_exists('get_table_serial')){

    function get_table_serial($table)
    {
        return SysSerial::generate($table);
    }
}

/**
 * @param $mobile
 * @return null|string|string[]
 * 隐藏手机号
 */
if(!function_exists('get_replace_mobile')){

    function get_replace_mobile($mobile)
    {
        return preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $mobile);
    }
}

if(!function_exists('get_replace_nickname')){

    function get_replace_nickname($nickname)
    {
        return mb_substr($nickname, 0, 1, 'UTF-8').'***'.mb_substr($nickname, -1, 1, 'UTF-8');
    }
}
/**
 * @return string
 * 获取当前用户的IP
 */
if(!function_exists('get_ip')){

    function get_ip()
    {
        if(!empty($_SERVER['HTTP_CLIENT_IP'])){
            //如果变量是非空或非零的值，则 empty()返回 FALSE。
            $IP = explode(',', $_SERVER['HTTP_CLIENT_IP']);
        }elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
            $IP = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        }elseif(!empty($_SERVER['REMOTE_ADDR'])){
            $IP = explode(',', $_SERVER['REMOTE_ADDR']);
        }else{
            $IP[0] = 'None';
        }
        return $IP[0];
    }
}
/**
 * @param $lat2
 * @param $lng2
 * @return float
 * 微信用户距离某经纬度距离
 */
if(!function_exists('get_distance')){

    function get_distance($lat2, $lng2)
    {
        $lat1 = isset($_COOKIE['lat']) ? $_COOKIE['lat'] : '';
        $lng1 = isset($_COOKIE['lng']) ? $_COOKIE['lng'] : '';
        if(empty($lat1) || empty($lng1)) return 0;
        return get_real_distance($lat1, $lng1, $lat2, $lng2);
    }
}

/**
 * @param $lat1
 * @param $lng1
 * @param $lat2
 * @param $lng2
 * @return float
 * 根据经纬度计算两点之间距离
 */
if(!function_exists('get_real_distance')){
    function get_real_distance($lat1, $lng1, $lat2, $lng2)
    {
        $earthRadius = 6367000; //approximate radius of earth in meters

        $lat1 = ($lat1*pi())/180;
        $lng1 = ($lng1*pi())/180;

        $lat2 = ($lat2*pi())/180;
        $lng2 = ($lng2*pi())/180;

        $calcLongitude = $lng2-$lng1;
        $calcLatitude = $lat2-$lat1;
        $stepOne = pow(sin($calcLatitude/2), 2)+cos($lat1)*cos($lat2)*pow(sin($calcLongitude/2), 2);
        $stepTwo = 2*asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius*$stepTwo;

        return number_format(sprintf("%.2f", $calculatedDistance/1000), 1);
    }
}

/**
 * @return bool
 * 判断是否是在微信浏览器里
 */
if(!function_exists('is_weixin_browser')){

    function is_weixin_browser()
    {
        $agent = $_SERVER ['HTTP_USER_AGENT'];
        if(!strpos($agent, "MicroMessenger")){
            return false;
        }
        return true;
    }
}

/**
 * @param $userId
 * @param $status
 * @return bool
 * 获取用户不同状态的数量
 */
if(!function_exists('get_user_order_num')){

    function get_user_order_num($userId, $status)
    {
        if(!is_array($status) || empty($userId)){
            return false;
        }
        $builder = \App\Models\Order\OrdOrder::where('buyer_id', $userId)->where('refer', \App\Models\Order\OrdOrder::ORDER_REFER_MEMBER);
        if(in_array(\App\Models\Order\OrdOrder::ORDER_STATUS_FINISHED, $status)){
            $num = $builder->whereIn('status', $status)->where('assess_at', null)->count();
        }else{
            $num = $builder->whereIn('status', $status)->count();
        }
        return $num;
    }
}

if(!function_exists('get_domain_prefix')){
    function get_domain_prefix()
    {
        $url = request()->url();
        if(!$url){
            return null;
        }
        $urls = parse_url($url);
        $host = $urls['host'];
        $segment = explode('.', $host)[0];
        $segment = strtolower($segment);
        return $segment;
    }
}

/**
 * @param int $length
 * @return string
 * 生成10位随机兑换码
 */
if(!function_exists('get_code')){
    function get_code($length = 10)
    {
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $code = '';
        for($i = 0; $i < $length; $i++){
            $code .= $chars[mt_rand(0, strlen($chars)-1)];
        }
        return $code;
    }
}
if(!function_exists('get_number')){
    function get_number($length = 10)
    {
        $chars = '0123456789';
        $number = '';
        for($i = 0; $i < $length; $i++){
            $number .= $chars[mt_rand(0, strlen($chars)-1)];
        }
        return $number;
    }
}

/**
 * @param string $guard
 * @param $table
 * @param $id
 * @param null $storeId
 * @return bool
 * 判断用户是否加入收藏
 */
if(!function_exists('is_favorite')){

    function is_favorite($guard = 'web', $table, $id, $storeId = null)
    {
        if(!auth($guard)->check()) return false;
        $user = auth($guard)->user();
        $query = \App\Models\Base\SysFavorite::where('model_id', $id)->where('model_type', $table)->where('user_id', $user->id);
        if(!empty($storeId)){
            $query = $query->where('store_id', $storeId);
        }
        $favorite = $query->first();
        return !empty($favorite) ? true : false;

    }
}

/**
 * 显示筛选条件
 * @param string $rank
 * @return array|mixed
 */
if(!function_exists('get_rank')){
    function get_rank(string $rank = '')
    {
        $ranks = ['all' => '综合排序', 'comment' => '好评优先', 'distance' => '距离最近'];
        return isset($ranks[$rank]) ? $ranks[$rank] : $ranks;
    }
}

/**
 * @param $name
 * @param $val
 * @param int $expire
 * @param string $path
 * @param string $domain
 * 存储cookie
 */
if(!function_exists('set_cookie')){

    function set_cookie($name, $val, $expire = 1, $path = '/')
    {
        $domain = env('APP_DOMAIN');
        $expire > 0 ? $expire = time()+$expire : $expire; //cookie时间
        if(empty($domain)){
            setcookie($name, $val, $expire, $path);
        }else{
            setcookie($name, $val, $expire, $path, $domain);
        }
        return $_COOKIE[$name] = $val;
    }
}

/**
 * @param $name
 * @param string $path
 * @param string $domain
 * 删除cookie
 */
if(!function_exists('del_cookie')){

    function del_cookie($name, $path = '/')
    {
        $domain = env('APP_DOMAIN');
        set_cookie($name, '', time()-3600, $path, $domain);
        $_COOKIE[$name] = '';
        unset($_COOKIE[$name]);
    }
}

/**
 * @param $name
 * @return bool
 * 获取cookie
 */
if(!function_exists('get_cookie')){

    function get_cookie($name)
    {
        if(!empty($_COOKIE[$name])){
            return $_COOKIE[$name];
        }
        return false;
    }
}

if(!function_exists('error')){
    function error($message, $context = [])
    {
        return app('log')->error($message, $context);
    }
}

if(!function_exists('minierror')){
    function minierror($message, $context = []) {
        $appid = $appid ?? request()->header('appid', env('MALL_APPID'));
        $context['params'] = request()->all();
        return app(LogContract::class)
            ->set('logFileName', 'applets')
            ->set('isDate',true)
            ->set('logName', $appid)
            ->logError($message, $context);
    }
}

if(!function_exists('logsql')){
    function logsql($builder){
        $bindings = $builder->getBindings();
        $sql = str_replace('?', '%s', $builder->toSql());
        $sql = sprintf($sql, ...$bindings);
        logger($sql);
    }
}

/**
 * 取汉字的第一个字的首字母
 * @param type $str
 * @return string|null
 */
if(!function_exists('get_first_charter')){
    function get_first_charter($str)
    {
        if(empty($str)){
            return '';
        }
        $fchar = ord($str{0});
        if($fchar >= ord('A') && $fchar <= ord('z')){
            return strtoupper($str{0});
        }
        $s1 = iconv('UTF-8', 'gb2312', $str);
        $s2 = iconv('gb2312', 'UTF-8', $s1);
        $s = $s2==$str ? $s1 : $str;
        $asc = ord($s{0})*256+ord($s{1})-65536;
        if($asc >= -20319 && $asc <= -20284){
            return 'A';
        }
        if($asc >= -20283 && $asc <= -19776){
            return 'B';
        }
        if($asc >= -19775 && $asc <= -19219){
            return 'C';
        }
        if($asc >= -19218 && $asc <= -18711){
            return 'D';
        }
        if($asc >= -18710 && $asc <= -18527){
            return 'E';
        }
        if($asc >= -18526 && $asc <= -18240){
            return 'F';
        }
        if($asc >= -18239 && $asc <= -17923){
            return 'G';
        }
        if($asc >= -17922 && $asc <= -17418){
            return 'H';
        }
        if($asc >= -17417 && $asc <= -16475){
            return 'J';
        }
        if($asc >= -16474 && $asc <= -16213){
            return 'K';
        }
        if($asc >= -16212 && $asc <= -15641){
            return 'L';
        }
        if($asc >= -15640 && $asc <= -15166){
            return 'M';
        }
        if($asc >= -15165 && $asc <= -14923){
            return 'N';
        }
        if($asc >= -14922 && $asc <= -14915){
            return 'O';
        }
        if($asc >= -14914 && $asc <= -14631){
            return 'P';
        }
        if($asc >= -14630 && $asc <= -14150){
            return 'Q';
        }
        if($asc >= -14149 && $asc <= -14091){
            return 'R';
        }
        if($asc >= -14090 && $asc <= -13319){
            return 'S';
        }
        if($asc >= -13318 && $asc <= -12839){
            return 'T';
        }
        if($asc >= -12838 && $asc <= -12557){
            return 'W';
        }
        if($asc >= -12556 && $asc <= -11848){
            return 'X';
        }
        if($asc >= -11847 && $asc <= -11056){
            return 'Y';
        }
        if($asc >= -11055 && $asc <= -10247){
            return 'Z';
        }
        return null;
    }
}

/**
 * 分享/扫码参数资源
 * @param string $module 模块
 * @param int $skuId 单品ID
 * @param int $tenantId 租客ID
 * @param int $storeId 门店ID
 * @param string $scene 粉丝来源类型 scan 扫码 share 分享
 * @return string
 */
if(!function_exists('get_source_encrypt')){
    function get_source_encrypt(array $params)
    {
        $openid = array_get($params, 'openid');
        $skuId = array_get($params, 'sku_id', 0);
        $tenantId = array_get($params, 'tenant_id', 0);
        $storeId = array_get($params, 'store_id', 0);
        $scene = array_get($params, 'scene', 'scan');
        $guideId = array_get($params, 'guide_id', 0);
        $url = array_get($params, 'url', null);
        return set_encrypt('openid:'.$openid.'|sku:'.$skuId.'|tenant:'.$tenantId.'|store:'.$storeId.'|scene:'.$scene.'|guide:'.$guideId.'|url:'.$url);
    }
}

/**
 * 数组/字符串加密
 * @return string
 */
if(!function_exists('set_encrypt')){
    function set_encrypt($string)
    {
        return urlencode(str_encrypt($string, 'E'));
    }
}

/**
 * 字符串解密
 * @return string/array
 */
if(!function_exists('get_decrypt')){
    function get_decrypt($string)
    {
        return str_encrypt(urldecode($string), 'D');
    }
}

/**
 * 函数名称:str_encrypt
 * 函数作用:加密解密字符串
 * $operation:判断是加密还是解密:E:加密   D:解密
 * $key :加密的钥匙(密匙)
 */
if(!function_exists('str_encrypt')){
    function str_encrypt($string, $operation, $key = 'cw')
    {
        $key = md5($key);

        if(is_array($string)){
            $string = http_build_query($string);
        }
        $key_length = strlen($key);
        $string = $operation=='D' ? base64_decode($string) : substr(md5($string.$key), 0, 9).$string;
        $string_length = strlen($string);
        $rndkey = $box = array();
        $result = '';
        for($i = 0; $i <= 255; $i++){
            $rndkey[$i] = ord($key[$i%$key_length]);
            $box[$i] = $i;
        }
        for($j = $i = 0; $i < 256; $i++){
            $j = ($j+$box[$i]+$rndkey[$i])%256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }
        for($a = $j = $i = 0; $i < $string_length; $i++){
            $a = ($a+1)%256;
            $j = ($j+$box[$a])%256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));
        }
        if($operation=='D'){
            if(substr($result, 0, 9)==substr(md5(substr($result, 9).$key), 0, 9)){
                $result = substr($result, 9);
                if(strpos($result, '&')){
                    parse_str($result, $output);
                    return $output;
                }
                $output = json_decode($result, true);
                if(is_array($output)){
                    return $output;
                }
                return $result;
            }else{
                return '';
            }
        }else{
            return str_replace('=', '', base64_encode($result));
        }
    }
}

/**
 * 绑定粉丝url
 * @$source encryp过签名串
 * @token 分享者key
 */
if(!function_exists('get_bindfans_url')){
    function get_bindfans_url(string $source, string $token = '')
    {
        $params['source'] = $source;
        $token && $params['token'] = $token;
        return env('APP_API_URL').'/callback/bindfans'.'?'.http_build_query($params);
    }
}

/**
 * 判断是否为wap浏览器
 */
if(!function_exists('get_wap_brower')){
    function get_wap_brower()
    {
        // 先检查是否为wap代理，准确度高
        if((isset ($_SERVER['HTTP_VIA']) && stristr($_SERVER['HTTP_VIA'], "wap")) || isset ($_SERVER['HTTP_X_WAP_PROFILE'])){
            return true;
        }  //检查USER_AGENT
        elseif(isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |Googlebot-Mobile|YahooSeeker\/M1A1-R2D2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $_SERVER['HTTP_USER_AGENT'])){
            return true;
        }// 检查浏览器是否接受 WML.
        elseif(isset ($_SERVER['HTTP_ACCEPT'])){//协议法，因为有可能不准确，放到最后判断
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml')!==FALSE) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html')===FALSE || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))){
                return true;
            }
        }
        return false;
    }
}

/**
 * 获取租客类型
 */
if(!function_exists('get_tenant_type')){
    function get_tenant_type($type, $alls = [])
    {
        if(empty($alls)){
            $alls = \App\Models\Tenant\TntTenant::getAllTypes();
        }
        $result = [];
        foreach($alls as $key => $value){
            if($key&$type){
                $result[$key] = $value;
            }
        }
        return $result;
    }
}

/**
 * @param $phone
 * @return bool
 * 验证座机或手机号
 */
if(!function_exists('check_contact_info')){

    function check_contact_info($phone)
    {
        $isMob = "/^1[34578]{1}\d{9}$/";
        $isTel = "/^([0-9]{3,4}-)?[0-9]{7,8}$/";
        if(!preg_match($isMob, $phone) && !preg_match($isTel, $phone)){
            return false;
        }else{
            return true;
        }
    }
}

/**
 * @param $phone
 * @return bool
 * 生成6位随机验证码
 */
if(!function_exists('setCode')){

    function setCode()
    {
        $code = str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);
        return $code;
    }
}


/**
 * @param $number
 * @param string $type
 * @return int
 * 将小时换算成小时或天
 */
if(!function_exists('get_hour_day')){
    function get_hour_day($number, $type = 'day')
    {
        $a = intval($number);//把$number小时，换算成天和小时
        $m = 8;
        $day = intval($a/$m);
        $hour = $a%$m;
        return $type=='day' ? ($number==0 ? 0 : $day) : ($number==0 ? 0 : $hour);
    }
}

/**
 * @param $tenantId
 * @return bool
 * 检查商家交易设置是否开启只能会员才可以交易
 */
if(!function_exists('check_tenant_order_member')){
    function check_tenant_order_member($tenantId)
    {
        $tenant_order_setting = tenant_setting('order', $tenantId);
        if($tenant_order_setting['member']==1){
            return true;
        }
        return false;
    }
}

/**
 * @param $tenantId
 * @return bool
 * 检查商家是否创建了会员卡
 */
if(!function_exists('check_tenant_created_card')){
    function check_tenant_created_card($tenantId)
    {
        $card = CrmCard::where('tenant_id', $tenantId)->first();
        if($card){
            return true;
        }
        return false;
    }
}

/**
 * @param $userId User表id
 * @param $tenantId
 * @return bool
 * 检查是否用户下单时是否显示激活会员卡提示语
 */
if(!function_exists('check_show_activate_card_words')){
    function check_show_activate_card_words($userId, $tenantId)
    {
        if(check_tenant_order_member($tenantId) && check_tenant_created_card($tenantId)){
            $crmuser = CrmUser::where('user_id', $userId)->where('tenant_id', $tenantId)->first();
            if($crmuser){
                $user_card = CrmCardUser::where('user_id', $crmuser['id'])->where('tenant_id', $tenantId)->first();
                if(!$user_card){
                    // 该用户还没有该商家会员卡,显示提示语
                    return true;
                }
            }else{
                // 不是商家会员,肯定没有开卡
                return true;
            }
        }
        // 商家没有打开订单配置,商家没有建卡,都不显示提示语
        return false;
    }
}

/**
 * @param $user (导购数据)
 * @param $url
 * @return string
 * 导购分享链接
 */
if(!function_exists('get_guide_qrcode')){
    function get_guide_qrcode($user, $url, $model, $storeId)
    {
        $url = get_guide_qrcode_url($user, $url, $storeId);
        return qrcode($model, $url);
    }
}
/**
 * @param $user
 * @param $url
 * @param $storeId
 * @return string
 * 导购绑定粉丝链接
 */
function get_guide_qrcode_url($user, $url, $storeId)
{
    return get_bindfans_url(get_source_encrypt(['model' => 'guide', 'tenant_id' => $user->tenant_id, 'store_id' => $storeId, 'scene' => 'scan', 'guide_id' => $user->id, 'url' => get_http_url($url, 'weixin')]));
}

/**
 * @param $user
 * @return mixed
 * 判断当前用户角色,默认导购角色
 */
if(!function_exists('is_user_role')){
    function is_user_role($user, $tenantId=null, $storeId=null, $role = \App\Models\Tenant\TntUserHasGroup::ROLE_GUIDER)
    {
       if (!$tenantId || !$storeId) {
           return false;
       }

        $tntHasGroup = \App\Models\Tenant\TntUserHasGroup::query()->storeStaff($tenantId,$storeId,$role,$user->id)->first();

        return !empty($tntHasGroup['id']) ? true : false;
    }
}
if(!function_exists('is_mobile')){
    function is_mobile()
    {
        if(is_weixin_browser()){
            return true;
        }
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if(isset($_SERVER['HTTP_X_WAP_PROFILE'])){
            return true;
        }
        // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if(isset($_SERVER['HTTP_VIA'])){
            // 找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        }
        // 脑残法，判断手机发送的客户端标志,兼容性有待提高。其中'MicroMessenger'是电脑微信
        if(isset($_SERVER['HTTP_USER_AGENT'])){
            $clientkeywords = array('nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile', 'MicroMessenger');
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if(preg_match("/(".implode('|', $clientkeywords).")/i", strtolower($_SERVER['HTTP_USER_AGENT']))){
                return true;
            }
        }
        // 协议法，因为有可能不准确，放到最后判断
        if(isset ($_SERVER['HTTP_ACCEPT'])){
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml')!==false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html')===false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))){
                return true;
            }
        }
        return false;
    }
}
/**
 * @param $sku
 * @param $storeId
 * @return string
 * 生成门店sku商品二维码
 */
if(!function_exists('get_sku_qrcode')){
    function get_sku_qrcode($sku, $storeId = 0, $size = 200) {
        return normal_qrcode(get_http_url('goods/index?store_id=' . $storeId . '&storeId=' . $storeId . '&id=' . $sku->id, 'weixin'), 'png', $size);
    }
}

/**
 * 生成缩略图
 * @param $path
 * @param $width
 * @param $height
 */
if(!function_exists('image_thumb')){
    function image_thumb($imgName, $width = 100, $height = 100, $expiredAt = 60)
    {
        try{
            $pathinfo = pathinfo($imgName);
            $fileName = $pathinfo['dirname'].'/'.$pathinfo['filename'].$width.'x'.$height.'.'.$pathinfo['extension'];
            $img = \Intervention\Image\Facades\Image::cache(function($image) use ($imgName, $fileName, $width, $height){
                $image->make(public_path($imgName))->resize($width, $height)->save(public_path($fileName));
            }, $expiredAt);
            return $fileName;
        }catch(\Exception $ex){
            error(__CLASS__ . ' | ' . __FUNCTION__ . ' | ' . $ex->getFile() . ' | ' . $ex->getLine() . ' | error = ' . $ex->getMessage());
            return $imgName;
        }
    }
}

/**
 * 日志写入操作
 * @param $params
 */
if(!function_exists('get_logger_encrypt')){
    function get_logger_encrypt(array $params)
    {
        $userCard = array_get($params, 'user_card', '');
        $storeId = array_get($params, 'store_id', 0);
        $guideId = array_get($params, 'guide_id', 0);
        $type = array_get($params, 'type', 0);
        $itemId = array_get($params, 'item_id', 0);
        $itemType = array_get($params, 'item_type', null);
        $channel = array_get($params, 'channel', 0);
        $intro = array_get($params, 'intro', null);
        $visitorModel = array_get($params, 'visitor_model');
        return set_encrypt('user_card:'.$userCard.'|guide_id:'.$guideId.'|type:'.$type.'|item_id:'.$itemId.'|item_type:'.$itemType.'|channel:'.$channel.'|intro:'.$intro.'|visitor_model:'.$visitorModel.'|store_id:'.$storeId);
    }
}
/**
 * @param $min
 * @param $max
 * @return string
 * 指定范围内生成保留小数点两位随机数
 */
if(!function_exists('rand_float')){

    function rand_float($min, $max)
    {
        $number = $min+mt_rand()/mt_getrandmax()*($max-$min);
        return number_format($number, 2);
    }
}
/**
 * @return mixed
 * 随机调取卡片信息
 */
if(!function_exists('rand_message')){

    function rand_message($key = '')
    {
        $arr = config('wechat.share_info');
        $rndKey = !empty($key) ? (int)$key : array_rand($arr);

        return $arr[$rndKey];
    }
}

/**
 * @param string $key
 * @return mixed
 * 随机调取卡片模版
 */
if(!function_exists('rand_key')){

    function rand_key()
    {
        $arr = config('wechat.share_info');
        return array_rand($arr);
    }
}

/**
 * @return mixed
 * 随机调取背景图片
 */
if(!function_exists('rand_images')){

    function rand_images($type)
    {
        $arr = config('wechat.'.$type.'_bg');
        $rndKey = array_rand($arr);
        return $arr[$rndKey];
    }
}

/**
 * @desc 前台页面输出金额函数
 * @param floatval $k 金额
 * @return 0.00
 */
if(!function_exists('get_moneyit')){
    function get_moneyit($k)
    {
        return rtrim(rtrim(sprintf('%.2f', $k), '0'), '.');
    }
}

/**
 * @param $price
 * @return string
 * 商品价格万为单位
 */
if(!function_exists('get_price')){

    function get_price($price)
    {
        if($price > 10000){
            return number_format($price/10000, 2).'万';
        }
        return number_format($price, 2);
    }
}

/**
 * @param string $key key
 * @param array $replace 参数替换值
 * @param null $prefix 位置（tenant，www，admin）
 * @param string $lang
 *
 * @return array|string|null
 */
if (!function_exists('L')) {
    function L($key, $replace = [], $prefix = null, $lang = 'zh-CN') {
        is_null($prefix) && $prefix = get_domain_prefix();
        return __($prefix . '.' . $key, $replace, $lang);
    }
}


/** @desc 测试环境关闭,过滤商圈/品牌测试数据
 * @param $collection collection
 * @return collection
 */
if(!function_exists('filter_dev_data')) {
    function filter_dev_data($collection) {
        $collect = $collection->first();
        if(!$collect instanceof App\Models\Base\SysSquare && !$collect instanceof App\Models\Goods\GdsBrand) {
            return $collection;
        }
        if(!env('APP_MINIPRO_ENV_TEST',0)) {
            $lists = $collection->filter(function($value) {
                return $value['is_dev'] == 0;
            });
            if($collection instanceof LengthAwarePaginator) {
                return new LengthAwarePaginator($lists, $lists->count(), $collection->perPage(), $collection->currentPage());
            }
            return $lists;
        }
        return $collection;
    }
}


/* @param $price
 * @return string
 * 商品价格万为单位
 */
if(!function_exists('get_price')) {

    function get_price($price)
    {
        if ($price > 10000) {
            return number_format($price / 10000, 2) . '万';
        }
        return number_format($price, 2);
    }
}

if(!function_exists('number_to_chinese')){
    /**
     * @param $num
     * @return mixed|string
     * 数字转中文
     */
    function number_to_chinese($num)
    {
        if (is_int($num) && $num < 100) {
            $char = array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
            $unit = ['', '十', '百', '千', '万'];
            $return = '';
            if ($num < 10) {
                $return = $char[$num];
            } elseif ($num%10 == 0) {
                $firstNum = substr($num, 0, 1);
                if ($num != 10) $return .= $char[$firstNum];
                $return .= $unit[strlen($num) - 1];
            } elseif ($num < 20) {
                $return = $unit[substr($num, 0, -1)]. $char[substr($num, -1)];
            } else {
                $numData = str_split($num);
                $numLength = count($numData) - 1;
                foreach ($numData as $k => $v) {
                    if ($k == $numLength) continue;
                    $return .= $char[$v];
                    if ($v != 0) $return .= $unit[$numLength - $k];
                }
                $return .= $char[substr($num, -1)];
            }
            return $return;
        }
    }
}
